<template>
  <!-- 头以下 -->
  <div class="layout-col plr15 pb15">
    <div class="ww100 flex-bc mb15 white">
      <div class="flex-sc">
        <span class="pb8 pt10 plr20 mr15 cursor" v-for="(v, i) in state.typeList" :key="i" :class="v.type == state.type? 'tabStyle':''" @click="state.type = v.type; init()">
          <span :class="v.type == state.type? 'textStyle':''">{{v.name}}</span>
        </span>
      </div>
      <div class="flex-ec flex1 h32">
        <img class="ml5 cursor" src="@/assets/images/e1.png" @click="state.styleType = '2'">
        <img class="ml5 cursor" src="@/assets/images/e2.png" @click="state.styleType = '4'">
        <img class="ml5 cursor" src="@/assets/images/e3.png" @click="state.styleType = '9'">
        <span class="i21 cursor ml20" @click="toPath('/controllog')">操作记录</span>
      </div>
    </div>
    <div v-if="!state.empty" class="ww100 flex1 overlay tc flex-ss warp hidden">
      <div v-for="(v, i) in state.list.filter(a=>!state.type || a.type == state.type)" :key="i" 
      class="borderstyle relative p20 rad10 bs hidden flex-col" 
      :class="state.styleType=='2'?'list2-15':state.styleType=='4'?'list3-15':'list4-15'" 
      style="box-sizing: border-box;"
      element-loading-background="rgba(0, 0, 0, 0.3)"
      v-loading="state.clickIndex == v.id && state.loading? true : false"
      element-loading-text="遥控中...">
        <div class="absolute t20 r20 cursor flex-col" v-if="v.action && !isNull(v.action.kgArr)">
          <div class="flex-sc mb20" v-for="(vv, ii) in v.action.kgArr" :key="ii" @click.stop="remote(v, 'kg', vv)">
            <div v-if="v.action.kgArr.length>1" class="fw mr10 ww100">{{vv.code_name}}</div>
            <img v-if="v[vv.mark] == 0" class="ww100" src="@/assets/images/icon1.png">
            <img v-if="v[vv.mark] == 1" class="ww100" src="@/assets/images/icon11.png">
          </div>
        </div>
        <div class="flex-col ww100">
          <div class="flex-sc"><div :class="v.offline != 0?'bga':'bgi21'" class="rad100 w10 h10 mt2 mr8"></div>{{v.name}}</div>
          <div class="flex-sc mt10 ml18">
            <div class="mr8">位置:</div>
            <div>{{v.instlPos}}</div>
          </div>
        </div>
        <div class="flex-bc ww100 flex1">
          <div class="flex1 flex-cc mr20" :class="v.offline != 0?'gray':''">
            <img class="ww40" src="@/assets/images/door.png" v-if="v.type=='access_ctrl'">
            <img class="ww40" src="@/assets/images/f1.png" v-else-if="v.type=='air_conditioner'">
            <img class="ww40" src="@/assets/images/f2.png" v-else-if="v.type=='TH'">
            <img class="ww40" src="@/assets/images/f9.png" v-else-if="v.type=='camera'">
            <img class="ww40" src="@/assets/images/f4.png" v-else-if="v.type=='water_immersion'">
            <img class="ww40" src="@/assets/images/f8.png" v-else-if="v.type=='EICollector'">
            <img class="ww40" src="@/assets/images/f7.png" v-else-if="v.type=='switch'">
            <img class="ww40" src="@/assets/images/f7.png" v-else>
          </div>
          <div class="flex1 flex-col-cs">
            <div class="flex-ss" v-if="v.action && !isNull(v.action.modeArr)">
              <span class="mr20">模式</span>
              <div class="flex-sc warp flex1">
                <div class="flex-sc cursor mr20 mb10" v-for="(vv, ii) in v.action.modeArr" :key="ii" @click="remote(v, 'mode', vv)">
                  <img class="w16 mr5" src="@/assets/images/icon2.png" v-if="v.mode == vv.action">
                  <img class="w16 mr5" src="@/assets/images/icon22.png" v-else>
                  <span>{{vv.name}}</span>
                </div>
              </div>
            </div>
            <div class="flex-ss" v-if="v.action && !isNull(v.action.speedArr)">
              <span class="mr20">速度</span>
              <div class="flex-sc warp flex1">
                <div class="flex-sc cursor mr20 mb10" v-for="(vv, ii) in v.action.speedArr" :key="ii" @click="remote(v, 'speed', vv)">
                  <img class="w16 mr5" src="@/assets/images/icon2.png" v-if="v.speed == vv.action">
                  <img class="w16 mr5" src="@/assets/images/icon22.png" v-else>
                  <span>{{vv.name}}</span>
                </div>
              </div>
            </div>
            <div class="flex-sc mt5" v-if="v.action && !isNull(v.action.countArr)">
              <div class="w16 mt5 cursor" v-if="v.action.countArr[0]" @click="remote(v, 'count', v.action.countArr[0])">
                <img class="ww100" src="@/assets/images/icon3.png">
              </div>
              <span class="f20 mlr20" :class="v.isAlarm > 0? 'i8': ''">{{!isNull(v.valArr)?v.valArr[0]:'/'}} {{!proxy.isNull(v.dwArr)? v.dwArr[0] : ''}}</span>
              <div class="w16 mt5 cursor" v-if="v.action.countArr[1]" @click="remote(v, 'count', v.action.countArr[1])">
                <img class="ww100" src="@/assets/images/icon33.png">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="state.empty" class="flex1 tc flex-cc fw f30">设置类型控制点</div>
  </div>
</template>

<script lang="ts" setup>
  import api from '@/api'
  import scheduled from "@/utils/scheduled";
  const { createScheduled } = scheduled();
  const { proxy }: any = getCurrentInstance();
  const configStore = proxy.configStore();
  const publicStore = proxy.publicStore();
  const state = reactive({
    ...publicStore.$state,
    clickIndex: '-1',
    styleType: '2',
    typeList: [],
    type: '',
    initParams: {}
  });

  onMounted(async () => {
    await getInit()
    init();
    // createScheduled('init', 5*60*1000, () => { init() })
  });

  const getInit = async() => {
    let query = {"o": "o_sensor", "p": [publicStore.distributId], "i": 0}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    let sensorList = proxy.isNull(res)? [] : res
    let query2 = getQuery(sensorList)
    let params2 = {queryApi2: query2}
    let res2 = await publicStore.post(params2)
    state.typeList = getTypeList(res2)
    state.list = getList(res)
    state.empty = proxy.isNull(state.list)? true : false
    getParams()
    init()
  }

  const getQuery = (val) => {
    let tempArr = [] 
    val.filter(a=>a.class == 0).forEach(v => {
      let exist = tempArr.find(a=>a.p[0] == v.type)
      if(!exist) tempArr.push({"o":"o_sensor_template_control_property","p":[v.type]})
    })
    return tempArr
  }

  const getTypeList = (val, val2) => {
    let tempArr = [{name: '全部', type: ''}]
    val.forEach(v => {
      let exist = tempArr.find(a=>a.type == v.sensor_type)
      // if(!exist && v.sensor_type != 'access_ctrl')
      if(!exist) tempArr.push({name: proxy.find(configStore.templateList, ['type', v.sensor_type], 'name'), type: v.sensor_type})
    })
    return tempArr
  }

  const getList = (val) => {
    let tempArr = [] 
    state.typeList.forEach(v => {
      let list = val.filter(a=> a.type == v.type)
      if(list) tempArr = tempArr.concat(list)
    })
    return tempArr
  }

  const getParams = async() => {
    let queryArr1 = []
    let queryArr2 = []
    let queryArr3 = []
    state.list.forEach(v => {
      let query1 = {"o": "o_sensor_control_action", "p":[v.id], "i": 0}
      let query2 = {"o":"o_r_sensor", "p":[v.id], "i": 1}
      let query3 = {"o":"o_sensor_cfg_property", "p":[v.id], "i": 0}
      queryArr1.push(query1)
      queryArr2.push(query2)
      queryArr3.push(query3)
    })
    state.initParams = {queryApi1: queryArr1, queryApi2: queryArr2, queryApi3: queryArr3}
  }
 
  const init = async() => { 
    let res = await publicStore.post(state.initParams)
    let queryApi1 = proxy.isNull(res.queryApi1)? [] : res.queryApi1
    let queryApi2 = proxy.isNull(res.queryApi2)? [] : res.queryApi2
    let queryApi3 = proxy.isNull(res.queryApi3)? [] : res.queryApi3
    state.list.forEach(v => {
      let action = queryApi1.filter(a=>a.sensor_id == v.id)
      let r_sensor = queryApi2.find(a=>a.sensor_id == v.id)
      let cfg_sensor = queryApi3.filter(a=>a.sensor_id == v.id)
      Object.assign(v, r_sensor)
      v.action = !proxy.isNull(action)? setAction(action) : []
      let tempArr = setValue(cfg_sensor, r_sensor)
      v.valArr = !proxy.isNull(r_sensor) && !proxy.isNull(cfg_sensor)? tempArr[0] : []
      v.dwArr = !proxy.isNull(r_sensor) && !proxy.isNull(cfg_sensor)? tempArr[1] : []
      v.mode = v['6160']? v['6160'] : ''
      v.speed = v['6162']? v['6162'] : ''
      if(v.type == "access_ctrl"){
        v.kg = v['doorState']? v['doorState'] : ''
      }else{
        v.kg = v['6156']? v['6156'] : ''
        v.kg1 = ''
        if(v['6160']) v.kg1 = v['6160']
        if(v['6164']) v.kg1 = v['6164']
      }
    })
    console.log('state.list', state.list)
  }

  const setAction = (action) => {
    // 开关action_type => kg 
    // 计数action_type => count
    // 模式action_type => mode
    let kgArr = []
    let countArr = []
    let modeArr = []
    let speedArr = []
    let i = 0
    action.forEach(v => {
      if(v.action_type.indexOf('kg') != -1) {
        let exist = kgArr.find(a=>a.code == v.code)
        if(exist){
          exist.kgArr.push(v)
        }else{
          let temp = {code: v.code, code_name: v.code_name, mark: 'kg' + (i==0?'': i), kgArr: [v]}
          kgArr.push(temp)
          i++
        }
      }
      if(v.action_type.indexOf('count') != -1) countArr.push(v)
      if(v.action_type.indexOf('mode') != -1) modeArr.push(v)
      if(v.action_type.indexOf('speed') != -1) speedArr.push(v)
    })
    return {kgArr: kgArr, countArr: countArr, modeArr: modeArr, speedArr: speedArr}
  }

  const setValue = (cfg_sensor, r_sensor) => {
    let valArr = []
    let dwArr = []
    cfg_sensor.forEach(v => {
      if(v.code.indexOf('vc_') != -1) valArr.push(v.value)
      if(v.code.indexOf('dw_') != -1) dwArr.push(v.value)
    })
    valArr.forEach((v, i) => {
      valArr[i] = r_sensor[v]?Math.round(r_sensor[v]*100)/100 : ''
    });
    return [valArr, dwArr]
  }

  const remote = async(val, remark, value = '') => {
    console.log('val----------', val)
    console.log('value----------', value)
    if(proxy.isNull(configStore.user)) return ElNotification({ title: '提示', message: '请完成登录', type: 'error' })
    state.clickIndex = val.id
    state.loading = true
    if(remark == 'kg') {
      let exist = val.action[remark + 'Arr'].find(a=>a.code == value.code)
      let value2 = exist[remark + 'Arr'].find(a=>a.action != val[value.mark])
      value = Object.assign(value, value2)
    }
    if(remark == 'count') {
      value = Object.assign({}, value)
      value.action = value.action == 'add'? parseInt(val.valArr[0]) + 1 + '': value.action == 'redu'? parseInt(val.valArr[0]) - 1 + '' : '0'
    }
    console.log('遥控value', value)
    value.startTime = new Date().getTime()
    let params = {sensor_id: value.sensor_id, code: value.code, action: value.action }
    api.remote([params]).then((res:any) => {
      if(res.errcode == 0){
        ElNotification({ title: '提示', message: '操作成功', type: 'success' })
        if(remark == 'mode') val[remark] = value.action
        if(remark == 'speed') val[remark] = value.action
        if(remark == 'count') val.valArr[0] = parseInt(value.action)
        if(remark == 'kg') val[value.mark] = value.action
        setRecord(val, value, 1)
      }else{
        setRecord(val, value, 2)
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
      }
    }).catch((err) => {
        setRecord(val, value, 2)
        ElNotification({ title: '提示', message: '操作失败', type: 'error' })
    })
  }

  const setRecord = async(val, value, res) => {
    state.loading = false
    let form = {
      id: new Date().getTime(),
      sensor_id: val.id,
      sensor_name: val.name,
      instlPos: val.instlPos,
      stationNum: publicStore.distributId,
      code: value.code,
      code_name: value.code_name,
      action: value.action,
      action_name: value.name,
      orther: '',
      userName: configStore.user.name,
      startTime: value.startTime,
      endTime: new Date().getTime(),
      result: res,
      o: 'o_sensor_control_log',
      a: '新增',
      t: 'add',
    }
    console.log('遥控记录----------', form)
    api.updateApi([form]).then((res:any) => {
      if(res.errcode == 0){
        console.log('遥控记录----------', res)
      }
    }).catch((err) => {
      ElNotification({ title: '提示', message: '记录失败', type: 'error' })
    })
  }

  </script>
  
  <style scoped lang="scss">
    .tabStyle{
      background: linear-gradient(0deg, #242DAB 1%, rgba(12,1,67,0.00) 100%);
      border-bottom: 2px solid rgba(65, 255, 255, 0.5);
    }
    .textStyle{
      background: linear-gradient(180deg, #ffffff 0%, #64DEFF 100%);
      background-clip: text;
      -webkit-text-fill-color: transparent;
      box-sizing: border-box;
    }
  </style>
  